<template>
    <el-form :model="ruleForm" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="ruleForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="Login()">登录</el-button>
            <el-button type="primary" @click="Getyzm()">获取验证码</el-button>
            <el-button type="primary" @click="YkLogin()">游客登录</el-button>
            <el-button type="primary" @click="EmailLogin()">邮箱登录</el-button>
            <el-button type="primary" @click="TwoLogin()">二维码登录</el-button>
            <el-button type="primary" @click="CheckLoginStatus()">验证登录状态</el-button>
            <el-button @click="resetForm()">重置</el-button>
        </el-form-item>


        <!-- 验证码弹窗 -->
        <el-Dialog title="提示" :visible.sync="dialogVisibleyzm" width="30%" :before-close="handleClose">
            <el-input v-model="ruleForm.phone" disabled />
            <el-input v-model="ruleForm.yzm" placeholder="请输入验证码" />
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click='Verify()'>验证验证码</el-button>
                <el-button @click="dialogVisibleyzm = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisibleyzm = false">确 定</el-button>
            </span>
        </el-dialog>



        <!-- 二维码弹窗 -->
        <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <!-- 加载状态提示 -->
            <div v-if="isLoading" class="loading-container" style="text-align: center; padding: 20px;">
                <i class="el-icon-loading" style="font-size: 24px; color: #409EFF;"></i>
                <p style="margin-top: 10px;">加载中...</p>
            </div>

            <div v-if="!isLoading" style="text-align: center;">
                <img :src="qrCodeUrl" alt="二维码" style="width: 200px; height: 200px;" v-if="qrCodeUrl && !qrError">
                <p v-if="!qrCodeUrl && !qrError && !isLoading">二维码加载中...</p>
                <p v-if="qrError" style="color: red;">二维码加载失败，请重试</p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </el-form>
</template>
<script>
import QRCode from 'qrcode'
import { Getyzm, Loginphone, YKLogin, EmailLogin, Gettwo, Gettwoimg, Verify, CheckLoginStatus, Checktwo } from '../api/login'
export default {
    name: 'Login',
    data() {
        return {
            ruleForm: {
                phone: '15222767758',
                password: '',
                yzm: '',
                email: '2385845046@qq.com'
            },
            //控制二维码弹出的开关
            dialogVisible: false,
            //控制验证码弹出的开关
            dialogVisibleyzm: false,
            // 二维码key
            qrCodeUrl: '',
            isLoading: false,  // 加载状态
            qrError: false,     // 错误状态
            pollingTimer: null // 轮询定时器

        };
    },
    methods: {
        async Login() {
            // 对手机号和密码进行 URL 编码处理
            const encodedData = {
                phone: encodeURIComponent(this.ruleForm.phone),
                password: encodeURIComponent(this.ruleForm.password)
            };

            try {
                let res = await Loginphone(encodedData);
                console.log(res);
            } catch (error) {
                console.error('登录请求失败:', error);
            }
        },
        //获取验证码
        async Getyzm() {
            this.dialogVisibleyzm = true
            let res = await Getyzm(
                this.ruleForm.phone
            )
            console.log(res)
        },
        //验证验证码
        async Verify() {
            let res = await Verify(this.ruleForm)
            console.log(res)
            if (res.code == 200) {
                this.$message({
                    message: '验证码正确',
                    type: 'success'
                });
                this.dialogVisibleyzm = false
            }
        },
        //游客登录 获取cookie
        async YkLogin() {
            let res = await YKLogin()
            console.log(res)

        },
        //邮箱登录
        async EmailLogin() {

            const emailData = { email: this.ruleForm.email }
            let res = await EmailLogin(emailData)
            console.log(res)
        },

        //二维码登录
        async TwoLogin() {
            try {
                // 开始加载
                this.isLoading = true;
                this.qrError = false;
                this.qrCodeUrl = '';
                this.dialogVisible = true

                //先获取key
                const keyRes = await Gettwo()
                const key = keyRes.data.unikey
                // console.log(key)

                //使用key获取二维码图片
                const imgRes = await Gettwoimg({ key: key })
                // 注意：根据网易云音乐API文档，应该是qrimg而不是qrurl
                this.qrCodeUrl = imgRes.data.qrimg || imgRes.data.qrurl

                //使用qrcode插件生成二维码
                const base64Url = await QRCode.toDataURL(this.qrCodeUrl, {
                    width: 200, // 二维码宽度
                    margin: 1 // 边距
                });
                this.qrCodeUrl = base64Url
                this.isLoading = false;
                this.startPolling(key)

            } catch (error) {
                console.error('二维码登录请求失败:', error);
                this.isLoading = false;
                this.qrError = true;
            }
        },

        //二维码检查
        // 启动轮询检查二维码状态
        startPolling(key) {
            // 先清除可能存在的旧轮询
            this.stopPolling();

            // 启动新轮询，每2秒检查一次
            this.pollingTimer = setInterval(async () => {
                try {
                    const res = await Checktwo({ key: key });
                    console.log('二维码状态检查:', res);
                    if(this.dialogVisible == false){
                        this.stopPolling()
                    }
                    // 根据API文档，800为二维码过期, 801为等待扫码, 802为待确认, 803为授权登录成功
                    switch (res.code) {
                        case 800:
                            // 二维码过期
                            this.stopPolling();
                            this.$message({
                                message: '二维码已过期，请重新获取',
                                type: 'warning'
                            });
                            this.dialogVisible = false;
                            break;
                        case 801:
                            // 等待扫码
                            console.log('请用微信扫二维码');
                            break;
                        case 802:
                            // 待确认
                            console.log('扫描成功，请在手机上确认');
                            break;
                        case 803:
                            // 授权登录成功
                            this.stopPolling();
                            this.$message({
                                message: '登录成功',
                                type: 'success'
                            });
                            // 保存cookie等用户信息
                            localStorage.setItem('cookie', res.cookie);
                            this.dialogVisible = false;
                            // 可以跳转到首页或其他操作
                            this.$router.push('/');
                            break;
                        default:
                            console.log('未知状态:', res);
                    }
                } catch (error) {
                    console.error('检查二维码状态失败:', error);
                    // 出错时停止轮询
                    this.stopPolling();
                }
            }, 6000); // 每2秒检查一次
        },

        // 停止轮询
        stopPolling() {
            if (this.pollingTimer) {
                console.log('停止轮询')
                clearInterval(this.pollingTimer);
                this.pollingTimer = null;
            }
        },
        //检查登录状态
        async CheckLoginStatus() {
            let res = await CheckLoginStatus();
            console.log(res)
        },

        //重置
        resetForm() {
            this.ruleForm = {
                phone: '',
                password: '',
                yzm: '',
                email: ''
            }
            if (this.ruleForm = {
                phone: '', password: '', yzm: '', email: ''
            }) {
                this.$message({
                    message: '重置成功',
                    type: 'success'
                });
            }
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => { });
        }
    }
}
</script>
<style scoped>
/* .el-form-item--feedback {
    width: 300px;
} */
</style>